<template> 
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          @click="handleSearchList()"
          type="primary"
          size="small">
          查询结果
        </el-button>
        <el-button
          style="float: right;margin-right: 15px"
          @click="handleResetSearch()"
          size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input style="width: 203px" v-model="listQuery.keyword" placeholder="商品名称"></el-input>
          </el-form-item>
          <el-form-item label="库存小于：">
            <el-input oninput="value=value.replace(/[^\d]/g,'')" style="width: 203px" v-model="listQuery.count"
                      placeholder="库存检索"></el-input>
          </el-form-item>
          <el-form-item label="书籍分类：">
            <el-cascader
              clearable
              @change="getSubjectList"
              v-model="selectProductCateValue"
              :options="productCateOptions">
            </el-cascader>
          </el-form-item>
          <el-form-item label="书籍科目：">
            <el-select v-model="listQuery.subjectId" placeholder="请选择科目" clearable>
              <el-option
                v-for="item in subjectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上架状态：">
            <el-select v-model="listQuery.state" placeholder="全部">
              <el-option
                v-for="item in publishStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推荐状态：">
            <el-select v-model="listQuery.recommend" placeholder="全部">
              <el-option
                v-for="item in recommendStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>

        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>

    </el-card>
    <div class="table-container">
      <el-table ref="productTable"
                :data="list"
                style="width: 100%"
                @selection-change="handleSelectionChange"
                v-loading="listLoading"
                border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="商品图片" width="120" align="center">
          <template slot-scope="scope"><img style="height: 80px" :src="store+scope.row.img"></template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">
            <p>{{ scope.row.name }}</p>
            <p>分类：{{ rowCate(scope.row.categoryId) }}</p>
            <p>科目：{{ rowSubject(scope.row.subjectId) }} | 库存：{{ scope.row.count }}</p>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">
            <p>价格：￥{{ scope.row.price }}</p>
          </template>
        </el-table-column>
        <el-table-column label="标签" width="140" align="center">
          <template slot-scope="scope">
            <p>上架：
              <el-switch
                @change="handlePublishStatusChange(scope.$index, scope.row)"
                :active-value="1"
                :inactive-value="0"
                v-model="scope.row.state">
              </el-switch>
            </p>
            <p>推荐：
              <el-switch
                @change="handleRecommendStatusChange(scope.$index, scope.row)"
                :active-value="1"
                :inactive-value="0"
                v-model="scope.row.recommend">
              </el-switch>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="排序" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.sort }}</template>
        </el-table-column>
        <el-table-column label="附件文件" width="140" align="center">
          <template slot-scope="scope">
            <p>普通文件：{{ scope.row.fileRelationList| getFile(0) }}</p>
            <p>音频文件：{{ scope.row.fileRelationList | getFile(1) }}</p>
            <p>
              <el-button size="small" @click="handleFile(scope.row)">查看文件</el-button>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="销量" width="100" align="center">
          <template slot-scope="scope">{{ scope.row.saleCount }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template slot-scope="scope">

            <el-button
              size="mini"
              @click="handleUpdateProduct(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="batch-operate-container">
      <el-select
        size="small"
        v-model="operateType" placeholder="批量操作">
        <el-option
          v-for="item in operates"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
      <el-button
        style="margin-left: 20px"
        class="search-button"
        @click="handleBatchOperate()"
        type="primary"
        size="small">
        确定
      </el-button>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15,20]"
        :current-page.sync="listQuery.pageNum"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      :title="editFileInfo.common?'操作普通文件':'操作音频文件'"
      :visible.sync="editFileInfo.dialogVisible"
      width="50%">
      <el-button size="small" @click="editFileInfo.common=true">普通文件</el-button>
      <el-button size="small" @click="editFileInfo.common=false">音频文件</el-button>
      <el-table
        ref="multipleTable"
        :data="computeFileList"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column
          label="编号"
          align="center"
          width="120">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column align="center"
                         label="文件名称">
          <template slot-scope="scope">
            <a :href="$store.getters.store+scope.row.file.store" class="is-link" :download="scope.row.file.fileName">
              {{ scope.row.file.fileName }} <i class="el-icon-download"></i>
            </a>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" width="160">
          <template slot-scope="scope">
            {{ getSizeWithExt(scope.row.file.size) }}
          </template>
        </el-table-column>
        <el-table-column label="优先级" align="center" width="120">
          <template slot-scope="scope" align="center">
            <el-input-number size="small" style="width: 100%" v-model="scope.row.sort"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column align="center" label="下载次数">
          <template slot-scope="scope" align="center">
            {{ scope.row.download }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="scope">
            <el-button size="small" @click="updateFileSort(scope.row)">修改</el-button>
            <el-button type="danger" size="small" @click="deleteFile(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchList,
  updateDeleteStatus,
  updateRecommendStatus,
  updatePublishStatus, getSubjectAll, getCategoryListAll, getFileList
} from '@/api/product'
import {getCategoryTree} from '@/api/productCate'
import {deleteFile, getFileByBid, getSubjectList, updateFileRelationSort} from "@/api/book";
import {formatFileSize} from "@/utils/index"

const defaultListQuery = {
  keyword: null,
  pageNum: 1,
  pageSize: 10,
  state: null,
  recommend: null,
  categoryId: null,
  subjectId: null,
  count: null
};

const initEditFileInfo = {
  dialogVisible: false,
  productId: null,
  fileList: [],
  common: true
}
export default {
  name: "productList",
  data() {
    return {
      editFileInfo: Object.assign({}, initEditFileInfo),
      store: '',
      operates: [
        {
          label: "商品上架",
          value: "publishOn"
        },
        {
          label: "商品下架",
          value: "publishOff"
        },
        {
          label: "设为推荐",
          value: "recommendOn"
        },
        {
          label: "取消推荐",
          value: "recommendOff"
        }
      ],
      cateList: [],
      subjectList: [],
      operateType: null,
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: true,
      selectProductCateValue: null,
      multipleSelection: [],
      productCateOptions: [],
      // brandOptions: [],
      subjectOptions: [],
      publishStatusOptions: [{
        value: null,
        label: '全部'
      }, {
        value: 1,
        label: '上架'
      }, {
        value: 0,
        label: '下架'
      }],
      recommendStatusOptions: [{
        value: null,
        label: '全部'
      }, {
        value: 1,
        label: '推荐'
      }, {
        value: 0,
        label: '未推荐'
      }]
    }
  },
  created() {
    this.getList();
    this.getProductCateList();
    this.initDate();
    this.store = this.$store.getters.store
  },

  watch: {
    selectProductCateValue: function (newValue) {
      if (newValue != null && newValue.length == 2) {
        this.listQuery.productCategoryId = newValue[1];
      } else {
        this.listQuery.productCategoryId = null;
      }
    }
  },
  filters: {
    verifyStatusFilter(value) {
      if (value === 1) {
        return '审核通过';
      } else {
        return '未审核';
      }
    },
    getFile(val, target) {
      return val.filter((item) => item.type === target).length
    },

  },
  computed: {
    computeFileList() {
      let type = null
      if (this.editFileInfo.common) {
        type = 0
      } else {
        type = 1
      }
      return this.editFileInfo.fileList.filter(item => item.type === type)
    }
  },
  methods: {
    getSizeWithExt(size) {
      return formatFileSize(size)
    },
    updateFileSort(row) {
      console.log(row.id, row.sort)
      updateFileRelationSort(row.id, row.sort).then(
        res => {
          this.$message.success(res.message)
        }
      )
    },
    deleteFile(row) {
      this.$confirm('是否要进行删除操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id
        deleteFile(id).then(res => {
          this.$message.success(res.message)
          this.getList()
          getFileByBid(this.editFileInfo.productId).then(
            res => {
              this.editFileInfo.fileList = res.data
            }
          )
        })
      })
    },
    handleFile(row) {
      this.editFileInfo.productId = row.id;

      const map = row.fileRelationList.map(item => item.id);
      // console.log(map)
      getFileList(map).then(res => {
        if (res.data.length > 0) {
          this.editFileInfo.fileList = res.data.sort((x, y) => y.sort - x.sort);
          this.editFileInfo.dialogVisible = true;
        } else {
          this.$message.info("此书籍无附件文件，请到编辑处添加")
        }
      })
      // console.log(row)
    },
    rowSubject(val) {
      const filter = this.subjectList.filter(item => item.id == val);
      if (filter.length > 0)
        return filter[0].name
    },
    rowCate(val) {
      const cateArr = []
      const filter = this.cateList.filter(item => item.id === val);
      if (filter && filter.length > 0 && filter[0] !== undefined) {
        cateArr.unshift(filter[0].name);
        if (filter[0].parentId !== 0) {
          this.appendCateFather(cateArr, filter[0].parentId)
        }
      }
      if (cateArr.length > 1) {
        return cateArr.join(' | ')
      } else if (cateArr.length === 1) {
        return cateArr[0]
      }
      return '';
    },
    appendCateFather(cateArr, val) {
      const filter = this.cateList.filter(item => item.id === val);
      if (filter && filter.length > 0 && filter[0] !== undefined) {
        cateArr.unshift(filter[0].name);
        if (filter[0].parentId !== 0) {
          this.appendCateFather(cateArr, filter[0].parentId)
        }
      }
    },
    initDate() {
      getSubjectAll().then(res => {
        this.subjectList = res.data;
      })
      getCategoryListAll().then(res => {
        this.cateList = res.data;
      })
    },
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.listLoading = false;
        this.list = response.data.list;
        this.total = response.data.total;
      });
    },
    getSubjectList(val) {
      const categoryId = val[val.length - 1];
      this.subjectOptions = [];
      this.listQuery.categoryId = null;
      if (val.length > 0) {
        this.listQuery.categoryId = categoryId;
        getSubjectList(categoryId).then(
          response => {
            let subjectList = response.data;
            console.log(subjectList)
            for (let i = 0; i < subjectList.length; i++) {
              this.subjectOptions.push({label: subjectList[i].name, value: subjectList[i].id});
            }
          }
        )
      }


    },
    getProductCateList() {
      getCategoryTree().then(response => {
        let list = response.data;
        this.productCateOptions = [];
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({label: list[i].children[j].name, value: list[i].children[j].id});
            }
          }
          this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
        }
      });
    },

    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },
    handleAddProduct() {
      this.$router.push({path: '/pms/addProduct'});
    },
    handleBatchOperate() {
      if (this.operateType == null) {
        this.$message({
          message: '请选择操作类型',
          type: 'warning',
          duration: 1000
        });
        return;
      }
      if (this.multipleSelection == null || this.multipleSelection.length < 1) {
        this.$message({
          message: '请选择要操作的商品',
          type: 'warning',
          duration: 1000
        });
        return;
      }
      this.$confirm('是否要进行该批量操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
          ids.push(this.multipleSelection[i].id);
        }
        console.log(this.multipleSelection)
        switch (this.operateType) {
          case this.operates[0].value:
            //上架
            this.updatePublishStatus(1, ids);
            this.multipleSelection.forEach(item => {
              item.state = 1
            })
            break;
          case this.operates[1].value:
            this.updatePublishStatus(0, ids);
            this.multipleSelection.forEach(item => {
              item.state = 0
            })
            break;
          case this.operates[2].value:
            this.updateRecommendStatus(1, ids);
            this.multipleSelection.forEach(item => {
              item.recommend = 1
            })
            break;
          case this.operates[3].value:
            this.updateRecommendStatus(0, ids);
            this.multipleSelection.forEach(item => {
              item.recommend = 0
            })
            break;
          default:
            break;
        }
        // this.getList();
      });
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handlePublishStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      console.log(row)
      this.updatePublishStatus(row.state, ids);
    },
    handleNewStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updateNewStatus(row.newStatus, ids);
    },
    handleRecommendStatusChange(index, row) {
      let ids = [];
      ids.push(row.id);
      this.updateRecommendStatus(row.recommend, ids);
    },
    handleResetSearch() {
      this.selectProductCateValue = [];
      this.listQuery = Object.assign({}, defaultListQuery);
    },
    handleDelete(index, row) {
      this.$confirm('是否要进行删除操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = [];
        ids.push(row.id);
        this.updateDeleteStatus(1, ids);
      });
    },
    handleUpdateProduct(index, row) {
      this.$router.push({path: '/pms/updateProduct', query: {id: row.id}});
    },
    handleShowProduct(index, row) {
      console.log("handleShowProduct", row);
    },
    updatePublishStatus(publishStatus, ids) {
      let params = new URLSearchParams();
      params.append('ids', ids);
      params.append('publishStatus', publishStatus);
      updatePublishStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        });
      });
    },
    updateRecommendStatus(recommendStatus, ids) {
      let params = new URLSearchParams();
      params.append('ids', ids);
      params.append('recommendStatus', recommendStatus);
      updateRecommendStatus(params).then(response => {
        this.$message({
          message: '修改成功',
          type: 'success',
          duration: 1000
        });
      });
    },
    updateDeleteStatus(deleteStatus, ids) {
      let params = new URLSearchParams();
      params.append('ids', ids);
      params.append('deleteStatus', deleteStatus);
      updateDeleteStatus(params).then(response => {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 1000
        });
      });
      this.getList();
    }
  }
}
</script>
<style></style>


